<template>
  <div class="build-flow-container">
    <!-- 节点工具箱 -->
    <div class="node-toolbar">
      <div class="toolbar-title">审批节点</div>
      <div class="node-list">
        <div 
          v-for="node in approvalNodes" 
          :key="node.value" 
          class="node-item"
          :class="'node-' + node.value"
          draggable="true"
          @dragstart="handleDragStart($event, node)"
        >
          <i :class="node.icon"></i>
          <span>{{ node.label }}</span>
        </div>
      </div>
    </div>

    <!-- 流程设计画布 -->
    <div 
      class="flow-canvas"
      @dragover="handleDragOver"
      @drop="handleDrop"
    >
      <div v-if="flowNodes.length === 0" class="empty-hint">
        <i class="el-icon-plus"></i>
        <p>从左侧拖拽节点或点击添加节点按钮开始设计审批流程</p>
        <el-button type="primary" size="small" @click="addNode">添加节点</el-button>
      </div>

      <template v-else>
        <div 
          v-for="(node, index) in flowNodes" 
          :key="index"
          class="flow-node-wrapper"
        >
          <div 
            class="flow-node"
            :class="getNodeClass(node.type)"
          >
            <div class="node-header">
              <div class="node-title">
                <i :class="getNodeIcon(node.type)"></i>
                <span>{{ node.name }}</span>
              </div>
              <div class="node-actions">
                <i class="el-icon-edit" @click="editNode(node, index)"></i>
                <i class="el-icon-delete" @click="removeNode(index)"></i>
              </div>
            </div>
            <div class="node-content">
              <template v-if="node.type === 'approval'">
                <p v-if="node.approvalRole">审批角色: {{ getApprovalRoleName(node.approvalRole) }}</p>
                <p v-if="node.approvalUsers && node.approvalUsers.length">
                  审批人员: {{ formatApprovalUsers(node.approvalUsers) }}
                </p>
              </template>
              <template v-else-if="node.type === 'condition'">
                <p>条件表达式: {{ node.condition || '未设置' }}</p>
              </template>
              <template v-else-if="node.type === 'parallel'">
                <p>并行分支数: {{ node.branches || 2 }}</p>
              </template>
            </div>
          </div>
          <!-- 节点连接线，最后一个节点不显示 -->
          <div v-if="index < flowNodes.length - 1" class="node-connector">
            <i class="el-icon-arrow-down"></i>
          </div>
        </div>
      </template>
    </div>

    <!-- 节点编辑对话框 -->
    <el-dialog
      :title="nodeFormTitle"
      :visible.sync="nodeDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="nodeForm" :model="nodeForm" :rules="nodeRules" label-width="100px">
        <el-form-item label="节点名称" prop="name">
          <el-input v-model="nodeForm.name" placeholder="请输入节点名称"></el-input>
        </el-form-item>

        <!-- 审批节点特有字段 -->
        <template v-if="nodeForm.type === 'approval'">
          <el-form-item label="审批角色" prop="approvalRole">
            <el-select v-model="nodeForm.approvalRole" placeholder="请选择审批角色">
              <el-option label="部门经理" value="dept_manager"></el-option>
              <el-option label="总监" value="director"></el-option>
              <el-option label="副总" value="vice_president"></el-option>
              <el-option label="总经理" value="president"></el-option>
              <el-option label="财务负责人" value="finance_manager"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="审批人员" prop="approvalUsers">
            <el-select 
              v-model="nodeForm.approvalUsers" 
              multiple 
              placeholder="请选择审批人员"
              :loading="userLoading"
            >
              <el-option 
                v-for="user in userList" 
                :key="user.userId" 
                :label="user.userName" 
                :value="user.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>

        <!-- 条件节点特有字段 -->
        <template v-if="nodeForm.type === 'condition'">
          <el-form-item label="条件表达式" prop="condition">
            <el-input 
              v-model="nodeForm.condition" 
              placeholder="请输入条件表达式"
              type="textarea"
              :rows="3"
            ></el-input>
            <div class="form-tip">
              支持表达式，例如：amount>1000 && dept=='财务部'
            </div>
          </el-form-item>
        </template>

        <!-- 并行节点特有字段 -->
        <template v-if="nodeForm.type === 'parallel'">
          <el-form-item label="分支数量" prop="branches">
            <el-input-number 
              v-model="nodeForm.branches" 
              :min="2" 
              :max="5"
            ></el-input-number>
          </el-form-item>
          
          <el-form-item label="完成条件" prop="completeCondition">
            <el-radio-group v-model="nodeForm.completeCondition">
              <el-radio label="all">全部分支完成</el-radio>
              <el-radio label="any">任一分支完成</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="nodeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNodeForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getApproverList } from '@/api/supply/flowTemplate';

export default {
  name: "BuildFlow",
  props: {
    // 审批节点类型
    approvalNodes: {
      type: Array,
      default: () => []
    },
    // 初始流程数据
    initData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 流程节点列表
      flowNodes: [],
      // 节点对话框可见性
      nodeDialogVisible: false,
      // 节点表单标题
      nodeFormTitle: '添加节点',
      // 节点表单
      nodeForm: {
        type: 'approval',
        name: '',
        approvalRole: '',
        approvalUsers: [],
        condition: '',
        branches: 2,
        completeCondition: 'all'
      },
      // 节点表单规则
      nodeRules: {
        name: [
          { required: true, message: '请输入节点名称', trigger: 'blur' }
        ],
        approvalRole: [
          { required: true, message: '请选择审批角色', trigger: 'change' }
        ],
        condition: [
          { required: true, message: '请输入条件表达式', trigger: 'blur' }
        ]
      },
      // 当前编辑节点索引
      editingIndex: -1,
      // 用户列表
      userList: [],
      // 用户加载状态
      userLoading: false
    };
  },
  created() {
    this.loadUsers();
    // 如果有初始数据，加载初始数据
    if (this.initData) {
      this.loadData(this.initData);
    }
  },
  methods: {
    // 加载用户列表
    loadUsers() {
      this.userLoading = true;
      getApproverList().then(response => {
        this.userList = response.rows || [];
        this.userLoading = false;
      }).catch(() => {
        this.userLoading = false;
      });
    },
    
    // 加载流程数据
    loadData(data) {
      if (data && data.nodes) {
        this.flowNodes = JSON.parse(JSON.stringify(data.nodes));
      }
    },
    
    // 获取流程数据
    getData() {
      return {
        nodes: this.flowNodes,
        version: '1.0'
      };
    },
    
    // 更新节点列表
    updateNodes(nodes) {
      this.flowNodes = JSON.parse(JSON.stringify(nodes));
    },
    
    // 重置
    reset() {
      this.flowNodes = [];
    },
    
    // 获取节点类样式
    getNodeClass(type) {
      return `node-${type}`;
    },
    
    // 获取节点图标
    getNodeIcon(type) {
      const nodeMap = {
        'approval': 'el-icon-s-check',
        'condition': 'el-icon-share',
        'parallel': 'el-icon-s-operation'
      };
      return nodeMap[type] || 'el-icon-s-operation';
    },
    
    // 获取审批角色名称
    getApprovalRoleName(roleKey) {
      const roleMap = {
        'dept_manager': '部门经理',
        'director': '总监',
        'vice_president': '副总',
        'president': '总经理',
        'finance_manager': '财务负责人'
      };
      return roleMap[roleKey] || roleKey;
    },
    
    // 格式化审批人员
    formatApprovalUsers(userIds) {
      if (!userIds || !userIds.length) return '无';
      
      const userNames = userIds.map(id => {
        const user = this.userList.find(u => u.userId == id);
        return user ? user.userName : id;
      });
      
      return userNames.join(', ');
    },
    
    // 处理拖拽开始
    handleDragStart(event, node) {
      event.dataTransfer.setData('node', JSON.stringify(node));
    },
    
    // 处理拖拽经过
    handleDragOver(event) {
      event.preventDefault();
    },
    
    // 处理拖拽放置
    handleDrop(event) {
      event.preventDefault();
      const nodeData = event.dataTransfer.getData('node');
      if (nodeData) {
        try {
          const node = JSON.parse(nodeData);
          this.showNodeDialog(node.value);
        } catch (e) {
          console.error('解析节点数据出错', e);
        }
      }
    },
    
    // 添加节点
    addNode() {
      // 显示节点类型选择
      this.$confirm('请选择要添加的节点类型', '添加节点', {
        confirmButtonText: '审批节点',
        cancelButtonText: '取消',
        distinguishCancelAndClose: true,
        type: 'info',
        center: true,
        showClose: false,
        roundButton: true,
        closeOnClickModal: false
      }).then(() => {
        this.showNodeDialog('approval');
      }).catch(action => {
        if (action === 'cancel') {
          return;
        }
      });
    },
    
    // 显示节点对话框
    showNodeDialog(nodeType) {
      this.nodeFormTitle = '添加节点';
      this.editingIndex = -1;
      this.nodeForm = {
        type: nodeType || 'approval',
        name: nodeType === 'approval' ? '审批节点' : 
              nodeType === 'condition' ? '条件节点' : 
              nodeType === 'parallel' ? '并行节点' : '新节点',
        approvalRole: '',
        approvalUsers: [],
        condition: '',
        branches: 2,
        completeCondition: 'all'
      };
      this.nodeDialogVisible = true;
    },
    
    // 编辑节点
    editNode(node, index) {
      this.nodeFormTitle = '编辑节点';
      this.editingIndex = index;
      this.nodeForm = JSON.parse(JSON.stringify(node));
      this.nodeDialogVisible = true;
    },
    
    // 移除节点
    removeNode(index) {
      this.$confirm('确认删除该节点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.flowNodes.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {});
    },
    
    // 提交节点表单
    submitNodeForm() {
      this.$refs.nodeForm.validate(valid => {
        if (valid) {
          const nodeData = JSON.parse(JSON.stringify(this.nodeForm));
          
          if (this.editingIndex > -1) {
            // 更新节点
            this.flowNodes.splice(this.editingIndex, 1, nodeData);
          } else {
            // 添加节点
            this.flowNodes.push(nodeData);
          }
          
          this.nodeDialogVisible = false;
          this.$message({
            type: 'success',
            message: this.editingIndex > -1 ? '更新节点成功' : '添加节点成功'
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.build-flow-container {
  display: flex;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  height: 600px;
}

.node-toolbar {
  width: 200px;
  border-right: 1px solid #ebeef5;
  background-color: #f5f7fa;
  padding: 15px;
  
  .toolbar-title {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dcdfe6;
  }
  
  .node-list {
    .node-item {
      display: flex;
      align-items: center;
      padding: 10px;
      margin-bottom: 10px;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
      cursor: move;
      background-color: #fff;
      user-select: none;
      
      &:hover {
        background-color: #f0f2f5;
      }
      
      &.node-approval {
        border-left: 3px solid #409EFF;
      }
      
      &.node-condition {
        border-left: 3px solid #67C23A;
      }
      
      &.node-parallel {
        border-left: 3px solid #E6A23C;
      }
      
      i {
        margin-right: 8px;
        font-size: 16px;
      }
    }
  }
}

.flow-canvas {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background-color: #fff;
  
  .empty-hint {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
    
    i {
      font-size: 32px;
      margin-bottom: 10px;
    }
    
    p {
      margin-bottom: 15px;
    }
  }
  
  .flow-node-wrapper {
    margin-bottom: 20px;
    
    .flow-node {
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      
      &.node-approval {
        border-left: 3px solid #409EFF;
        background-color: #ecf5ff;
      }
      
      &.node-condition {
        border-left: 3px solid #67C23A;
        background-color: #f0f9eb;
      }
      
      &.node-parallel {
        border-left: 3px solid #E6A23C;
        background-color: #fdf6ec;
      }
      
      .node-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .node-title {
          font-weight: bold;
          display: flex;
          align-items: center;
          
          i {
            margin-right: 5px;
          }
        }
        
        .node-actions {
          i {
            cursor: pointer;
            margin-left: 8px;
            font-size: 16px;
            
            &:hover {
              color: #409EFF;
            }
            
            &.el-icon-delete:hover {
              color: #F56C6C;
            }
          }
        }
      }
      
      .node-content {
        font-size: 13px;
        color: #606266;
        line-height: 1.5;
        
        p {
          margin: 5px 0;
        }
      }
    }
    
    .node-connector {
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      
      &:before {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: 50%;
        width: 2px;
        background-color: #dcdfe6;
        transform: translateX(-50%);
      }
      
      i {
        position: relative;
        z-index: 1;
        background-color: #fff;
        color: #dcdfe6;
      }
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 